class AdminsController < ApplicationController
  before_filter :authorize,:relogin_check, :except => [:new, :create]

  def new
    @user = User.new
  end

  def create
    if params[:user][:enterprise_id].present?
      @enterprise = Enterprise.find(params[:user][:enterprise_id]) 
      @enterprise.update_attributes :name => params[:enterprise_name]
    else
      @enterprise = Enterprise.create(:name => params[:enterprise_name])
      params[:user][:enterprise_id] = @enterprise.id
    end    
    @user = User.new(params[:user])
    if @user.save
      @enterprise.set_admin!(@user)
      session[:current_user_id] = @user.id
      @user.reset_login_token!
      cookies.signed[:login_token] = {
        :value => @user.login_token,
        :expires => 10.years.from_now
      } 
      redirect_to root_url
    else
      render :new
    end
  end
end
